package com.school.service.impl;

import com.github.pagehelper.PageInfo;
import com.school.dao.LikeWithUserMapper;
import com.school.dao.LikesMapper;
import com.school.dto.AdvancedLikes;
import com.school.dto.LikeWithUser;
import com.school.exception.LikesAlreadyExistException;
import com.school.exception.UserNotFoundException;
import com.school.model.*;
import com.school.utils.FileEnum;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

@Service
public class LikeServiceImpl {
    @Autowired
    UserServiceImpl userService;
    @Resource
    private LikesMapper likesMapper;

    @Autowired
    private SignServiceImpl signService;
    @Resource
    private LikeWithUserMapper likeWithUserMapper;

    @Autowired
    private PicServiceImpl picService;

    public void deleteByUserId(Integer userId) {
        Likes likes = new Likes();
        likes.setDeleted((byte) 1);
        likes.setLikeUserId(userId);
        LikesExample likesExample = new LikesExample();
        LikesExample.Criteria criteria = likesExample.createCriteria();
        criteria.andLikeUserIdEqualTo(userId);
        likesMapper.updateByExampleSelective(likes, likesExample);

        likes = new Likes();
        likes.setDeleted((byte) 1);
        likes.setLikedUserId(userId);
        likesExample = new LikesExample();
        criteria = likesExample.createCriteria();
        criteria.andLikeUserIdEqualTo(userId);
        likesMapper.updateByExampleSelective(likes, likesExample);
    }

    public PageInfo<LikeWithUser> querySelective(Integer year, String likeSchoolName, Integer page, Integer pageSize, String sort, String order, Likes.Column... columns) {
//        if (page != null && pageSize != null) {
//            PageHelper.startPage(page, pageSize);
//        }
        List<LikeWithUser> likeWithUsers = likeWithUserMapper.querySelective(year, likeSchoolName, page, pageSize, sort, order);
        return new PageInfo<>(likeWithUsers);
    }

    public void add(Likes like) throws UserNotFoundException, LikesAlreadyExistException {
        Integer likeUserId = like.getLikeUserId();
        Integer likedUserId = like.getLikedUserId();
        PageInfo pageInfo = querySelective(likedUserId, likeUserId);
        //说明已经有过该则意向了
        if (pageInfo.getList().size() != 0) {
            throw new LikesAlreadyExistException("该用户已经表明过意向了！");
        }
        User likeUser = userService.queryById(likeUserId);
        if (likeUser == null) {
            throw new UserNotFoundException("likeUserId用户id不存在！");
        }
        User likedUser = userService.queryById(likedUserId);
        if (likedUser == null) {
            throw new UserNotFoundException("likedUserId 用户id不存在！");
        }
        like.setUpdateTime(LocalDateTime.now());
        like.setAddTime(LocalDateTime.now());
        likesMapper.insertSelective(like);
    }

    public PageInfo<Likes> querySelective(Integer likeUserId, Integer likedUserId, Likes.Column... columns) {
        LikesExample likesExample = new LikesExample();
        LikesExample.Criteria criteria = likesExample.createCriteria();
        criteria.andDeletedEqualTo((byte) 0);
        if (Objects.nonNull(likeUserId)) {
            criteria.andLikeUserIdEqualTo(likeUserId);
        }
        if (Objects.nonNull(likedUserId)) {
            criteria.andLikedUserIdEqualTo(likedUserId);
        }
        List<Likes> likes = this.likesMapper.selectByExampleSelective(likesExample, columns);
        return new PageInfo<Likes>(likes);
    }

    public int count(Integer year, String likeSchoolName) {
        return likeWithUserMapper.count(year, likeSchoolName);
    }

    public List<Likes> querySelectiveDistinct(Integer year, String likeSchoolName, Integer page, Integer pageSize, String sort, String order) {
        return likeWithUserMapper.querySelectiveDistinct(year, likeSchoolName, page, pageSize, sort, order);
    }

    public int countDistinct(Integer year, String likeSchoolName) {
        return likeWithUserMapper.countDistinct(year, likeSchoolName);
    }

    public List<AdvancedLikes> retrieveAdvancedLikes(List<Likes> theLikes) {
        List<AdvancedLikes> advancedLikes = new LinkedList<>();
        for (Likes like : theLikes) {
            List<Likes> eachLikes = queryByLikeUserId(like.getLikeUserId());
            List<Sign> signs = signService.queryBySignUserId(like.getLikeUserId());
            List<Sign> signs1 = signService.queryBySignedUserId(like.getLikedUserId());
            signs.addAll(signs1);

            List<Likes> theUserThatLikesMe = queryByLikedUserId(like.getLikeUserId());

            List<Pics> logos = picService.querySelective(like.getLikeUserId(), FileEnum.LOGO.value());
            List<Pics> signatures = picService.querySelective(like.getLikeUserId(), FileEnum.SIGNATURE.value());
            User user = userService.queryById(like.getLikedUserId(), User.Column.schoolName);
            AdvancedLikes advancedLike = new AdvancedLikes(like.getLikeUserId(), user.getSchoolName(), signs, eachLikes, logos.size() > 0, signatures.size() > 0);
            advancedLikes.add(advancedLike);
        }
        return advancedLikes;
    }

    public List<Likes> queryByLikeUserId(Integer likeUserId) {
        LikesExample likesExample = new LikesExample();
        LikesExample.Criteria criteria = likesExample.createCriteria();
        criteria.andDeletedEqualTo((byte) 0);
        criteria.andLikeUserIdEqualTo(likeUserId);
        return likesMapper.selectByExampleSelective(likesExample);
    }

    private List<Likes> queryByLikedUserId(Integer likedUserId) {
        LikesExample likesExample = new LikesExample();
        LikesExample.Criteria criteria = likesExample.createCriteria();
        criteria.andDeletedEqualTo((byte) 0);
        criteria.andLikedUserIdEqualTo(likedUserId);
        return likesMapper.selectByExampleSelective(likesExample);
    }

//    public PageInfo<LikeWithUser> querySelective(Likes.Column... columns) {
//        PageInfo<LikeWithUser> likeWithUserPageInfo = querySelective(null, null, null, null, null, null, columns);
//        return likeWithUserPageInfo;
//    }

    public Collection<? extends Likes> queryById(Integer likeId) {
        LikesExample likesExample = new LikesExample();
        LikesExample.Criteria criteria = likesExample.createCriteria();
        criteria.andDeletedEqualTo((byte) 0);
        criteria.andIdEqualTo(likeId);
        return likesMapper.selectByExampleSelective(likesExample);
    }


    public Workbook exportLikesFormSingle(List<Likes> likesList) {
        Workbook workbook = new HSSFWorkbook();
        CellStyle cellStyle = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontName("IMPACT");
        font.setBold(true);
        cellStyle.setFont(font);
        Sheet sheet = workbook.createSheet();
        this.prepareSingle(cellStyle, sheet);
        int k = 0;
        for (Likes likes : likesList) {
            Row row = sheet.createRow(k + 2);
            Cell cell = row.createCell(0);
            User user1 = userService.queryById(likes.getLikeUserId(), User.Column.schoolName);
            cell.setCellValue(user1.getSchoolName());

            cell = row.createCell(1);
            User user2 = userService.queryById(likes.getLikedUserId(), User.Column.schoolName);
            cell.setCellValue(user2.getSchoolName());

            cell = row.createCell(2);
            cell.setCellValue(likes.getAddTime().toString());
            k++;
        }
        return workbook;

    }

    private void prepareSingle(CellStyle cellStyle, Sheet sheet) {
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("单项意向表");
        row = sheet.createRow(1);

        Cell cell = row.createCell(0);
        cell.setCellValue("学校名称");
        cell.setCellStyle(cellStyle);

        cell = row.createCell(1);
        cell.setCellValue("意向高校");
        cell.setCellStyle(cellStyle);

        cell = row.createCell(2);
        cell.setCellValue("提出时间");
        cell.setCellStyle(cellStyle);
    }


    public PageInfo<Likes> querySelective() {
        PageInfo<Likes> pageInfo = querySelective(null, null);
        return pageInfo;

    }

    public Workbook exportLikesForm(List<Likes> likes) {
        List<AdvancedLikes> advancedLikes = retrieveAdvancedLikes(likes);

        Workbook workbook = new HSSFWorkbook();
        CellStyle cellStyle = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontName("IMPACT");
        font.setBold(true);
        cellStyle.setFont(font);
        Sheet sheet = workbook.createSheet();
        this.prepare(cellStyle, sheet);

        for (int i = 0; i < advancedLikes.size(); i++) {
            Row row = sheet.createRow(i + 2);
            Cell cell = row.createCell(0);
            cell.setCellValue(advancedLikes.get(i).getSchoolName());

            cell = row.createCell(1);
            StringBuilder stringBuilder = new StringBuilder();
            List<Likes> likesList = advancedLikes.get(i).getLikesList();

            for (Likes likes1 : likesList) {
                User likeUser = userService.queryById(likes1.getLikeUserId(), User.Column.schoolName);
                User likedUser = userService.queryById(likes1.getLikedUserId(), User.Column.schoolName);
                if (advancedLikes.get(i).getUserId().equals(likes1.getLikeUserId())) {
                    stringBuilder.append(likedUser.getSchoolName()).append(",");
                } else {
                    stringBuilder.append(likeUser.getSchoolName()).append(",");
                }
            }
            deleteLastCharacter(stringBuilder);
            cell.setCellValue(stringBuilder.toString());

            cell = row.createCell(2);
            List<Sign> signList = advancedLikes.get(i).getSignList();
            stringBuilder = new StringBuilder();
            for (Sign sign : signList) {
                User signUser = userService.queryById(sign.getSignUserId(), User.Column.schoolName);
                User signedUser = userService.queryById(sign.getSignedUserId(), User.Column.schoolName);
                if (advancedLikes.get(i).getUserId().equals(sign.getSignUserId())) {
                    stringBuilder.append(signedUser.getSchoolName()).append(",");
                } else {
                    stringBuilder.append(signUser.getSchoolName()).append(",");
                }
            }
            deleteLastCharacter(stringBuilder);
            cell.setCellValue(stringBuilder.toString());

            cell = row.createCell(3);

            stringBuilder = new StringBuilder();
            List<Likes> likesList1 = advancedLikes.get(i).getLikesList();
            for (Likes likes1 : likesList1) {
                User likeUser = userService.queryById(likes1.getLikeUserId());
                User likedUser = userService.queryById(likes1.getLikedUserId());
                if (likes1.getSigned().equals((byte) 1)) {
                    if (likes1.getLikeUserId().equals(advancedLikes.get(i).getUserId())) {
                        stringBuilder.append(likedUser.getSchoolName()).append("(已接受 ").append(likes1.getUpdateTime()).append(")").append(",");
                    } else {
                        stringBuilder.append(likeUser.getSchoolName()).append("(已接受 ").append(likes1.getUpdateTime()).append(")").append(",");
                    }
                }
            }
            deleteLastCharacter(stringBuilder);
            cell.setCellValue(stringBuilder.toString());

            cell = row.createCell(4);
            if (advancedLikes.get(i).isHasLogo()) {
                cell.setCellValue("已上传");
            } else {
                cell.setCellValue("未上传");
            }
        }
        return workbook;
    }

    private void deleteLastCharacter(StringBuilder stringBuilder) {
        if (stringBuilder.length() > 0) {
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        }
    }

    public void prepare(CellStyle cellStyle, Sheet sheet) {
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("签约意向表");
        row = sheet.createRow(1);

        Cell cell = row.createCell(0);
        cell.setCellValue("学校名称");
        cell.setCellStyle(cellStyle);

        cell = row.createCell(1);
        cell.setCellValue("签约意向");
        cell.setCellStyle(cellStyle);

        cell = row.createCell(2);
        cell.setCellValue("签约匹配高校");
        cell.setCellStyle(cellStyle);

        cell = row.createCell(3);
        cell.setCellValue("被邀约情况");
        cell.setCellStyle(cellStyle);

        cell = row.createCell(4);
        cell.setCellValue("学校logo");
        cell.setCellStyle(cellStyle);
    }

    public void updateByIdSelective(Likes likes1) {
        likes1.setUpdateTime(LocalDateTime.now());
        this.likesMapper.updateByPrimaryKeySelective(likes1);
    }

    public int deleteById(Integer id) {
        return likesMapper.deleteByPrimaryKey(id);
    }
}
